package com.ldq.imooc.basics.socket;

import java.io.*;
import java.net.Socket;

/**
 * @Author : 李道泉
 * @Description :
 * @Date : 2018/4/23 16:04
 * @Modified by :
 */
public class TCPServerThread extends Thread {

    Socket socket = null;

    public TCPServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        OutputStream os = null;
        PrintWriter pw = null;
        try {
            //创建输入流读取客户端信息
            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println("Server，client001说：" + line);
            }
            socket.shutdownInput();

            //创建输出流响应客户端请求
            os = socket.getOutputStream();
            pw = new PrintWriter(os);
            pw.write("登陆成功，欢迎administrator！");
            pw.flush();

            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭相关资源
            try {
                if (pw != null) {
                    pw.close();
                }
                if (os != null) {
                    os.close();
                }

                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (is != null) {
                    is.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
            }
        }
    }
}
